package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Mapper类—>Host->Context->Wrapper->Servlet 该体系结构用于存储初始化加载到的Servlet信息
 */
public class Mapper {

    private String host;

    private int port;

    public static String appBase;

    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }


    public Map<String, HttpServlet> getServletMap() {
        return servletMap;
    }

    public void setServletMap(Map<String, HttpServlet> servletMap) {
        this.servletMap = servletMap;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(File app) {

        String appPath = app.getAbsolutePath().replaceAll("\\\\", "/");
        String webXmlPath = appPath + "/web.xml";

        //InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            InputStream inputStream = new FileInputStream(webXmlPath);

            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = "/" + app.getName() + servletMapping.selectSingleNode("url-pattern").getStringValue();
                //servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
                String className = servletClass.split("\\.")[1]; //LagouServlet
                String pack = app.getName()+"."+servletClass.split("\\.")[0]+".";  //demo1.server.
                String filePath = appPath+"/"+servletClass.split("\\.")[0]; //D:/javawork/lagou_work/webapps/demo2/server/

                servletMap.put(urlPattern, (HttpServlet) NewClassLoader.findClassByNameAndLocation(className, pack, new File(filePath)).newInstance());

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载解析server.xml
     */
    public void loadServer(){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element connector = (Element)rootElement.selectSingleNode("Service/Connector");
            port = Integer.valueOf(connector.attributeValue("port"));

            Element host = (Element)rootElement.selectSingleNode("Service/Engine/Host");
            String hostName = host.attributeValue("name");
            appBase = host.attributeValue("appBase");

            File appFile = new File(appBase);
            File[] apps = appFile.listFiles();

            for (File app : apps) {
                if(app.isDirectory()){
                    this.loadServlet(app);
                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


}
